<template>
    <el-select v-model="selectedClasses" multiple placeholder="请选择样式类" style="width: 100%">
        <el-option v-for="className in classOptions" :key="className" :label="className" :value="className" />
    </el-select>
</template>

<script setup>
import { ref, watch, inject, computed } from 'vue'

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => []
    }
})

const emit = defineEmits(['update:modelValue'])

const formConfig = inject('formConfig')

// 提取 CSS 中的 class 名称
const extractClassNames = (cssString) => {
    const matches = cssString.match(/\.(\w[\w-]*)\s*\{/g) || []
    return matches.map(m => m.match(/\.(\w[\w-]*)/)[1])
}

// 选项列表
const classOptions = computed(() => {
    if (!formConfig?.value?.globalStyle) return []
    return extractClassNames(formConfig.value.globalStyle)
})

// 当前选择值（本地维护）
const selectedClasses = ref([...props.modelValue])

watch(() => props.modelValue, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(selectedClasses.value)) {
    selectedClasses.value = [...newVal]
  }
})

watch(selectedClasses, (val) => {
  if (JSON.stringify(val) !== JSON.stringify(props.modelValue)) {
    emit('update:modelValue', val)
  }
})
</script>